package cn.jas.common.jascommon.context;

import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.RequestContextListener;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 获取RequestResponse过滤器
 */
public class RequestResponseFilter implements Filter {
    private static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
    private static final String HEADER_ORIGIN = "Origin";
    private static final String METHOD_OPTIONS = "OPTIONS";
    private static final String ALLOW_ORIGINS = "allowOrigins";
    private static final String REQUEST_ATTRIBUTES_ATTRIBUTE =
            RequestContextListener.class.getName() + ".REQUEST_ATTRIBUTES";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filter) throws IOException, ServletException {
        ServletRequestAttributes attributes = new ServletRequestAttributes(
                (HttpServletRequest) request, (HttpServletResponse) response);
        //request.setAttribute(REQUEST_ATTRIBUTES_ATTRIBUTE, attributes);
        HttpServletResponse  resp= (HttpServletResponse) response;
        HttpServletRequest  req= (HttpServletRequest) request;
        LocaleContextHolder.setLocale(request.getLocale());
        //RequestContextHolder.setRequestAttributes(attributes);
        String origin = req.getHeader(HEADER_ORIGIN);
        resp.addHeader(ACCESS_CONTROL_ALLOW_ORIGIN, origin);
        resp.addHeader("Access-Control-Allow-Methods", req.getHeader("Access-Control-Request-Method"));
        resp.addHeader("Access-Control-Allow-Headers", req.getHeader("Access-Control-Request-Headers"));
        if (req.getMethod().equalsIgnoreCase(METHOD_OPTIONS)) {
            resp.sendError(HttpServletResponse.SC_OK);
        } else {
            filter.doFilter(req, resp);
        }
    }


    @Override
    public void destroy() {
        RequestAttributes threadAttributes = RequestContextHolder.getRequestAttributes();
        if (threadAttributes != null) {
            LocaleContextHolder.resetLocaleContext();
            RequestContextHolder.resetRequestAttributes();
            if (threadAttributes instanceof ServletRequestAttributes) {
                ((ServletRequestAttributes) threadAttributes).requestCompleted();
            }
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // 什么也不做
    }

}
